import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;


class Confession{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }

}
@WebServlet("/confession")
public class ConfessionWall_datebase extends HttpServlet {
    private ObjectMapper mapper=new ObjectMapper();
    private DataSource dataSource=new MysqlDataSource();
    public void init(){
        ((MysqlDataSource)dataSource ).setUrl("jdbc:mysql://127.0.0.1:3306/java112?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource ).setUser("root");
        ((MysqlDataSource)dataSource ).setPassword("123456");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 其保存的作用，将 req 请求解析，并存储 起来
        Confession m=mapper.readValue(req.getInputStream(),Confession.class);

        System.out.println("收到的数据 ： " +m);

        try {
            save(m);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        resp.setStatus(200);
        resp.getWriter().write("ok");
        resp.getWriter().write(m.toString());

    }

    private void save(Confession m) throws SQLException {
        Connection connection= (Connection) dataSource.getConnection();
        // 2. 构造 SQL
        String sql = "insert into confession values(?, ?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, m.from);
        statement.setString(2, m.to);
        statement.setString(3, m.message);

        // 3. 执行 SQL
        statement.executeUpdate();

        // 4. 回收资源
        statement.close();
        connection.close();
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 当网页加载时，首先会发送一个 get 请求，我们这里就是在处理 get 请求
        // 首先返回一个 200 ok
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        /*resp.getWriter().write("ok");*/


        // 用来读取 list 中的数据
        List<Confession> messageList= null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        // 获取数据之后 将 数据转化为 js 格式 在传输过去
        String respJson=mapper.writeValueAsString(messageList);

        resp.getWriter().write(respJson);

    }

    private List<Confession> load() throws SQLException {

        List<Confession> list=new LinkedList<>();

        Connection connection= (Connection) dataSource.getConnection();

        String respond="select * from confession";
        PreparedStatement preparedStatement=connection.prepareStatement(respond);

        ResultSet resultSet =preparedStatement.executeQuery();

        while(resultSet.next()){
            Confession message=new Confession();
            message.from=resultSet.getString("from");
            message.to=resultSet.getString("to");
            message.message=resultSet.getString("message");

            list.add(message);
        }
        resultSet.close();
        preparedStatement.close();
        connection.close();
        return list;
    }
}
